package cn.zb.config.security;

import cn.zb.entity.auth.SysUser;
import cn.zb.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    SysUserMapper userMapper;

    /**
     * 登录时 自动调用 同时查询到角色与权限赋值
     * @param username  登录时 输入的账号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询对象
        SysUser user = userMapper.getByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 查询权限
        List<String> roles = userMapper.getRoles(username);
        List<String> perms = userMapper.getPerms(username);
        user.setRoles(roles);
        user.setPerms(perms);
        // 返回数据库查询到的实体对象 并将角色权限赋值后返回
        return user;
    }
}